package com.itstorm.pomeloweather.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.itstorm.pomeloweather.R;
import com.itstorm.pomeloweather.entity.PagerStatus;
import com.itstorm.pomeloweather.util.BroadcastCode;

public class MainActivity extends BaseActivity {

	private BroadcastReceiver mReceiver;
	private ViewPager viewPager;
	private SharedPreferences weatherList;
	private SharedPreferences.Editor editor;
	private String[] mAreas;
	private List<Fragment> fragmentList = new ArrayList<Fragment>();
	private PagerAdapter pagerAdapter;
	private List<PagerStatus> dataList = new ArrayList<PagerStatus>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.activity_main, null);
		setContentView(view);
		FragmentTransaction transaction = this.getSupportFragmentManager()
				.beginTransaction();
		transaction.commit();
		weatherList = getSharedPreferences("WeatherList", 0);
		editor = weatherList.edit();
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		viewPager = (ViewPager) findViewById(R.id.viewPager);
		getUserAreasData();
		pagerAdapter = new PagerAdapter(this.getSupportFragmentManager(),
				fragmentList);
		viewPager.setAdapter(pagerAdapter);
		setCurrentPage(0);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				Intent mIntent = new Intent();
				mIntent.setAction(BroadcastCode.changeAreas);
				mIntent.putExtra("type", BroadcastCode.changeArea);
				mIntent.putExtra("position", viewPager.getCurrentItem());
				MainActivity.this.sendBroadcast(mIntent);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
			}
		});

		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				if (intent.getAction().equals(BroadcastCode.changeAreas)) {
					Bundle extras = intent.getExtras();
					int type = extras.getInt("type", 0);
					switch (type) {
					case BroadcastCode.addArea:
						fragmentList.clear();
						dataList.clear();
						getUserAreasData();
						pagerAdapter.changeList(fragmentList);
						pagerAdapter.notifyDataSetChanged();
						viewPager.setCurrentItem(fragmentList.size() - 1, true);
						break;
					case BroadcastCode.delArea:
//						int index = extras.getInt("index", 0);
						fragmentList.clear();
						dataList.clear();
						getUserAreasData();
						pagerAdapter.changeList(fragmentList);
						pagerAdapter.notifyDataSetChanged();
						viewPager.setCurrentItem(fragmentList.size() - 1, true);
						break;
					case BroadcastCode.changeArea:
						int position = extras.getInt("position", 0);
						viewPager.setCurrentItem(position, false);
						break;
					default:
						break;
					}
				}
			}
		};
		IntentFilter mIntentFilter = new IntentFilter(BroadcastCode.changeAreas);
		registerReceiver(mReceiver, mIntentFilter);
	}

	public void setCurrentPage(int position) {
		viewPager.setCurrentItem(position, true);
	}

	public int getCurrentPage() {
		return viewPager.getCurrentItem();
	}

	class PagerAdapter extends FragmentStatePagerAdapter {

		private List<Fragment> viewList;

		public PagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
			super(fm);
			this.viewList = fragmentList;
		}

		public void changeList(List<Fragment> fragmentList) {
			this.viewList = fragmentList;
		}

		@Override
		public Fragment getItem(int arg0) {
			return (viewList == null || viewList.size() == 0) ? null : viewList
					.get(arg0);
		}

		@Override
		public int getItemPosition(Object object) {
			return PagerAdapter.POSITION_NONE;
		}

		@Override
		public int getCount() {
			return viewList == null ? 0 : viewList.size();
		}
	}

	private void getUserAreasData() {
		// TODO Auto-generated method stub
		weatherList = getSharedPreferences("WeatherList", 0);
		mAreas = weatherList.getString("Areas", "").split(",");

		for (int i = 0; i < mAreas.length; i++) {
			String areasName = mAreas[i];
			String json = weatherList.getString(areasName, "");
			PagerStatus mPagerStatus = new PagerStatus(areasName, json);
			dataList.add(mPagerStatus);

			fragmentList.add(new WeatherPageFragment(MainActivity.this, i,
					dataList.get(i)));
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		exitAlert();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		BaseActivity.slidingMenu.showMenu();
		return false;
	}

	private void exitAlert() {

		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.show();
		Window window = alertDialog.getWindow();
		WindowManager.LayoutParams layoutParams = window.getAttributes();
		layoutParams.gravity = (Gravity.CENTER);
		alertDialog.getWindow().setAttributes(layoutParams);
		window.setContentView(R.layout.dialog_defult);
		window.setBackgroundDrawableResource(android.R.color.transparent);
		TextView title = (TextView) window.findViewById(R.id.TextView_title);
		Button sure = (Button) window.findViewById(R.id.btn_dialog_top);
		Button cancel = (Button) window.findViewById(R.id.btn_dialog_bottom);
		title.setText("确定退出?");
		title.getPaint().setFakeBoldText(true);
		alertDialog.setCanceledOnTouchOutside(true);

		sure.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				MainActivity.this.finish();
			}
		});

		cancel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.cancel();
			}
		});
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}

}
